package com.codingclub.domain.handle.subject;

import com.codingclub.common.enums.ErrCode;
import com.codingclub.common.enums.SubjectInfoTypeEnum;
import com.codingclub.common.exception.BusinessException;
import com.codingclub.domain.bo.SubjectAnswerBO;
import com.codingclub.domain.bo.SubjectInfoBO;
import com.codingclub.infra.basic.entity.SubjectJudge;
import com.codingclub.infra.basic.entity.SubjectRadio;
import com.codingclub.infra.basic.service.SubjectJudgeService;
import com.codingclub.infra.basic.service.SubjectRadioService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 单选题目处理策略
 */
@Component
public class JudgeTypeHandler implements SubjectTypeHandler {
    private final SubjectJudgeService subjectJudgeService;

    //构造器注入
    public JudgeTypeHandler(SubjectJudgeService subjectJudgeService) {
        this.subjectJudgeService = subjectJudgeService;
    }

    @Override
    public SubjectInfoTypeEnum getHandlerType() {
        return SubjectInfoTypeEnum.RADIO;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public boolean add(SubjectInfoBO bo) {
        Long id = bo.getId();
        List<SubjectAnswerBO> answerBOS = bo.getAnswerBOS();
        if (id == null || answerBOS == null) {
            throw new BusinessException(ErrCode.PARAMS_ERROR);
        }
        List<SubjectJudge> judgeList = new ArrayList();
        for (SubjectAnswerBO answerBO : answerBOS) {
            //校验参数
            if (answerBO.getIsCorrect() == null) {
                throw new BusinessException(ErrCode.PARAMS_ERROR);
            }
            SubjectJudge subjectJudge = new SubjectJudge();
            BeanUtils.copyProperties(answerBO, subjectJudge);
            judgeList.add(subjectJudge);
        }
        return subjectJudgeService.batchInsert(judgeList);
    }
}
